#include "lru.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 * 函数：模拟LRU页面置换算法。
 *
 * @param queue_frames 一个字符串，表示页面访问序列。
 *                     字符串中的每个字符是一个数字，表示一个页面号。
 * @param num_frames   页框的数量，表示物理内存中可用的页框数。
 */
void
lru_page_replacement (char *queue_frames, int num)
{
  int frames[num];
  int counter[num];
  int time = 0;
  int len = strlen(queue_frames);

  for (int i = 0; i < num; i++) {
    frames[i] = -1;
    counter[i] = 0;
  }

  for (int i = 0; i < len; i++) {
    int page = queue_frames[i] - '0';
    int found = 0;

    if (page < 0) continue;

    for (int j = 0; j < num; j++) {
      if (frames[j] == page) {
        found = 1;
        counter[j] = ++time;
        break;
      }
    }

    if (!found) {
       int lru_index = 0;
       int lru_time = counter[0];

       for (int j = 1; j < num; j++) {
          if (counter[j] < lru_time) {
              lru_time = counter[j];
              lru_index = j;
          }
       }

       frames[lru_index] = page;
       counter[lru_index] = ++time;
    }

    printf("Access:%d,Frames: [", page);
        for (int j = 0; j < num; j++) {
          printf("%d", frames[j]);
          if (j < num - 1) {
            printf(",");
          }
        }
        printf("]\n");
  }
}
